package com.apache.uct.service.impl;

import java.util.List;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.uct.common.entity.Act;
import com.apache.uct.manager.ActManager;
import com.apache.uct.service.plugins.ActCacheHelper;

public class ActManagerImpl implements ActManager {

	protected IDao actDao;
	protected final String entityName = "com.apache.uct.common.entity.Act";

	public void setActDao(IDao actDao) {
		this.actDao = actDao;
	}

	public String saveInfo(ParamsVo<Act> vo) throws BusinessException {
		Act act = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="act_"+infoId;
		act.setActId(infoId);
		MethodParam param = new MethodParam("Act", cacheKey, "", entityName);
		param.setVaule(act);
		if (actDao.insert(param)) {
			updateSubCount(act.getFatherId(), true);
			return infoId;
		}
		return "";
	}

	public boolean editInfo(ParamsVo<Act> vo) throws BusinessException {
		Act act = vo.getObj();
		if (Validator.isNotNull(act.getActId())) {
			String cacheKey = "";
			//String cacheKey="act_"+act.getActId();
			MethodParam param = new MethodParam("Act", cacheKey, "", entityName);
			param.setVaule(act);
			return actDao.edit(param);
		}
		return false;
	}

	//修改子节点数(新增功删除时处发)
	private void updateSubCount(String fatherId, boolean isAdd) {
		if ("0".equals(fatherId))
			return;
		MethodParam param = new MethodParam("ById", "", "", entityName);
		param.setInfoId(fatherId);
		Act act = (Act) actDao.selectById(param);
		int count = 0;
		if (!Validator.isEmpty(act.getSubCount()))
			count = act.getSubCount();
		if (isAdd) {
			act.setSubCount(count + 1);
		} else {
			act.setSubCount(count + 1);
		}
		param = new MethodParam("Act", "", "", entityName);
		param.setVaule(act);
		actDao.edit(param);
	}

	public boolean deleteInfo(ParamsVo<Act> vo) throws BusinessException {
		String key = vo.getKey();
		boolean flag = false;
		if (Validator.isNull(key)) {
			String infoId = vo.getInfoId();
			if (Validator.isNull(infoId)) {
				return false;
			}
			String cacheKey = "";
			//String cacheKey="act_"+infoId;
			String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
			MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
			param.setInfoId(infoId);
			Act info = (Act) actDao.selectById(param);
			if (Validator.isEmpty(info)) {
				return false;
			}
			param.setVaule(info);//此处需要先将状态值赋值为删除状态
			if ("false".equals(mark)) {//逻辑删除
				param.setKey("Act");
				flag = actDao.edit(param);
			} else {
				param.setParams("actId", infoId);
				param.setDelete(true);
				flag = actDao.delete(param);
			}
			if (flag) {
				updateSubCount(info.getFatherId(), false);
			}
			return flag;
		} else if ("BySysEname".equals(key)) {
			String sysEname = String.valueOf(vo.getParams("sysEname"));
			MethodParam param = new MethodParam("BySysEname", "", actDao.getSql(7), entityName);
			param.setParams("sysEname", sysEname);
			param.setDelete(true);
			flag = actDao.delete(param);
		}
		if (flag) {
			ActCacheHelper.getInstance().delActCacheAll();
		}
		return flag;
	}

	public Object getInfoById(ParamsVo<Act> vo) {
		String infoId = vo.getInfoId();
		String cacheKey = "";
		//String cacheKey="act_"+infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		return actDao.selectById(param);
	}

	public Object execute(ParamsVo<Act> vo) {
		String key = vo.getKey();
		if ("userActAll".equals(key)) {
			return userActAll(vo);
		} else if ("userActAllList".equals(key)) {
			return userActAllList(vo);
		} else if ("userActVoAllList".equals(key)) {
			return userActVoAllList(vo);
		} else if ("userActByRoleId".equals(key)) {
			return userActByRoleId(vo, true);
		} else if ("checkActEname".equals(key)) {
			Act act = vo.getObj();
			return checkActEname(act.getFatherId(), act.getActEname());
		} else if ("actsByRoleIdOrUserId".equals(key)) {
			return userActByRoleId(vo, false);
		} else if ("ByActProperty".equals(key)) {
			String propertyName = String.valueOf(vo.getParams("propertyName"));
			String propertyValue = String.valueOf(vo.getParams("propertyValue"));
			return getActByProperty(propertyName, propertyValue);
		}
		return null;
	}

	private Act getActByProperty(String propertyName, String propertyValue) {
		MethodParam param = new MethodParam("ByProperty", "", "", entityName);
		param.setSqlStr(actDao.getSql(2) + propertyName + "=:" + propertyName);
		param.setParams(propertyName, propertyValue);
		List list = actDao.select(param);
		if (!Validator.isEmpty(list))
			return (Act) list.get(0);
		return null;
	}

	//验证权限标识是否存在
	private boolean checkActEname(String fatherId, String actEname) {
		MethodParam param = new MethodParam("ByActEnameAndFatherId", "", actDao.getSql(8), entityName);
		param.setParams("fatherId", fatherId);
		param.setParams("actEname", actEname);
		long count = actDao.count(param);
		if (count > 0)
			return false;
		return true;
	}

	//用户所有权限
	private Page userActAll(ParamsVo<Act> vo) {
		String userId = String.valueOf(vo.getParams("userId"));
		MethodParam param = new MethodParam("ByAllUserId", "", actDao.getSql(5), entityName);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		param.setParams("userId", userId);
		param.setParams("invalidTime", System.currentTimeMillis() + "");
		param.setResultCache(false);
		Page page = actDao.pageSelect(param);
		return page;
	}

	//用户所有权限
	private List userActAllList(ParamsVo<Act> vo) {
		String userId = String.valueOf(vo.getParams("userId"));
		MethodParam param = new MethodParam("ByAllUserId", "", actDao.getSql(5), entityName);
		param.setParams("userId", userId);
		param.setParams("invalidTime", System.currentTimeMillis() + "");
		param.setResultCache(false);
		return actDao.select(param);
	}

	//用户所有权限
	private List userActVoAllList(ParamsVo<Act> vo) {
		String userId = String.valueOf(vo.getParams("userId"));
		MethodParam param = new MethodParam("ByUserIdForActVo", "", actDao.getSql(5), entityName);
		param.setParams("userId", userId);
		param.setParams("invalidTime", System.currentTimeMillis() + "");
		param.setResultCache(false);
		return actDao.select(param);
	}

	//继承自角色的权限
	private Page userActByRoleId(ParamsVo<Act> vo, boolean isPage) {
		String userId = String.valueOf(vo.getParams("userId"));
		String roleId = String.valueOf(vo.getParams("roleId"));
		MethodParam param = new MethodParam("ByRoleId", "", "", entityName);
		if (isPage) {
			int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
			int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
			param.setPageIndex(pageIndex);
			param.setPageSize(pageSize);
		}
		if (Validator.isNotNull(userId)) {
			param.setSqlStr(actDao.getSql(6) + " and roleId in (select roleId from RoleGive where userId='" + userId
					+ "') )");
			param.setParams("userId", userId);
		}
		if (Validator.isNotNull(roleId)) {
			param.setSqlStr(actDao.getSql(6) + " and roleId ='" + roleId + "') )");
			param.setParams("roleId", roleId);
		}
		//param.setOrderby(" full_Ename ");
		param.setParams("invalidTime", System.currentTimeMillis() + "");
		param.setResultCache(false);
		Page page = actDao.pageSelect(param);
		return page;
	}

	public Page getPageInfo(ParamsVo<Act> vo) {
		String orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		param.setOrderby(" order_Num asc,create_Time desc");
		Page page = actDao.pageSelect(param);
		return page;
	}

	public List<Act> getList(ParamsVo<Act> vo) {
		String orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		param.setOrderby(" order_Num asc,create_Time desc");
		param.setResultCache(false);
		return actDao.select(param);
	}

	public long countInfo(ParamsVo<Act> vo) {
		MethodParam param = setMethodParams(vo, 1, "");
		return actDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<Act> vo, int type, String orderBy) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		StringBuffer sb = new StringBuffer(actDao.getSql(type));
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		Act act = vo.getObj();
		if (!Validator.isEmpty(act)) {
			if (Validator.isNotNull(act.getSysEname())) {
				sb.append(" and sysEname =:sysEname");
				param.setParams("sysEname", act.getSysEname());
			}
			if (Validator.isNotNull(act.getActEname())) {
				sb.append(" and actEname =:actEname");
				param.setParams("actEname", act.getActEname());
			}
			if (Validator.isNotNull(act.getActCname())) {
				sb.append(" and actCname =:actCname");
				param.setParams("actCname", act.getActCname());
			}
			if (Validator.isNotNull(act.getFullEname())) {
				sb.append(" and fullEname =:fullEname");
				param.setParams("fullEname", act.getFullEname());
			}
			if (Validator.isNotNull(act.getFullCname())) {
				sb.append(" and fullCname =:fullCname");
				param.setParams("fullCname", act.getFullCname());
			}
			if (Validator.isNotNull(act.getActType())) {
				sb.append(" and actType =:actType");
				param.setParams("actType", act.getActType());
			}
			if (Validator.isNotNull(act.getFatherId())) {
				sb.append(" and fatherId =:fatherId");
				param.setParams("fatherId", act.getFatherId());
			}
			if (Validator.isNotNull(act.getActUrl())) {
				sb.append(" and actUrl =:actUrl");
				param.setParams("actUrl", act.getActUrl());
			}
			if (Validator.isNotNull(act.getActRemark())) {
				sb.append(" and actRemark =:actRemark");
				param.setParams("actRemark", act.getActRemark());
			}
		}
		if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {//是否开启分级授权
			String orgId = String.valueOf(vo.getParams("userOrgId"));
			String deptId = String.valueOf(vo.getParams("userDeptId"));
			String sysUser = String.valueOf(vo.getParams("sysUser"));//是否为系统用户
			if (!"1".equals(sysUser)) {
				if (Validator.isNull(deptId)) {
					sb.append(" and actId in(select actId from ActGive where giveType='org' and roleId='" + orgId
							+ "')");
					param.setParams("actIds", orgId);
					param.setParams("giveType", "org");
				} else {
					sb.append(" and actId in(select actId from ActGive where giveType='dept' and roleId='" + deptId
							+ "')");
					param.setParams("actIds", deptId);
					param.setParams("giveType", "dept");
				}
			}
		}
		if (Validator.isNotNull(orderBy)) {
			sb.append(" order by orderNum asc,createTime desc");
		}
		param.setSqlStr(sb.toString());
		return param;
	}
}
